﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Diagnostics;

using FCNS.Utility;
using FCNS.KeepMoneyLibrary.Data;
using FCNS.KeepMoneyLibrary.Util;
using FCNS.KeepMoney.Util;

using BrightIdeasSoftware;

namespace FCNS.KeepMoney.Forms
{
    public partial class PurseForm : ParentForm
    {
        BankField bank = null;
        bool reloadEntryField = false;

        public PurseForm()
        {
            InitializeComponent();

            Program.Translation.ApplyTo(this);
        }

        private void PurseForm_Load(object sender, EventArgs e)
        {
            BannerFactory.CreateBannerEx(this, pictureBoxLogo, Properties.Resources.ba6_32,
                LanguageUtil.钱袋配置, LanguageUtil.设置用来存储收入与支出的账户);

            HotItemStyleUtil.SetHotItemStyle(listViewEntry, false);
            listViewEntry.AddDecoration(new EditingCellBorderDecoration(true));

            listViewEntry.SetObjects(BankField.GetBankField);
            for (int i = 0; i < BankField.GetBankField.Count; i++)
                if (!BankField.GetBankField[i].Enable)
                    listViewEntry.Items[i].ForeColor = Color.Red;
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            BankField bf = new BankField(LanguageUtil.新钱袋);
            bf.AddNewRowToDataTable();
            listViewEntry.SetObjects(BankField.GetBankField);
            for (int i = 0; i < BankField.GetBankField.Count; i++)
                if (!BankField.GetBankField[i].Enable)
                    listViewEntry.Items[i].ForeColor = Color.Red;
        }

        private void buttonEnable_Click(object sender, EventArgs e)
        {
            if (bank == null)
                return;

            if (bank.Default)
            {
                labelError.Text = LanguageUtil.默认钱袋不能禁用;
                return;
            }
            if (RegularEntryField.GetRegularEntryField.Find(gef => { return gef.BankId == bank.Id; }) != null)
            {
                labelError.Text = LanguageUtil.钱袋有未完成的定期账务_无法禁用;
                return;
            }
            bank.Enable = !bank.Enable;
            if (bank.Enable)
            {
                listViewEntry.SelectedItem.ForeColor = SystemColors.ControlText;
                buttonEnable.Text = LanguageUtil.禁用;
            }
            else
            {
                listViewEntry.SelectedItem.ForeColor = Color.Red;
                buttonEnable.Text = LanguageUtil.启用;
            }
            listViewEntry.Refresh();
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (bank == null)
                return;

            if (bank.Default)
            {
                labelError.Text = LanguageUtil.默认钱袋不能删除;
                return;
            }

            if (MessageBox.Show(LanguageUtil.此操作将移除其所属的所有账务记录_是否继续, "", MessageBoxButtons.YesNo) == DialogResult.No)
                return;

            bank.Remove();
            listViewEntry.SetObjects(BankField.GetBankField);
            reloadEntryField = true;
        }

        private void PurseForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Program.TheMainForm.UpdateUI(UIState.ConfigBankMenu);
            if (reloadEntryField)
                Program.TheMainForm.ReLoadEntry();

            Program.SaveKMD = true;
        }


        private void OnDefaultPurseChanged(object sender, SubItemCheckingEventArgs e)
        {
            labelError.ResetText();
            if (e.NewValue == CheckState.Unchecked)
            {
                e.Canceled = true;
                labelError.Text = LanguageUtil.默认钱袋不能取消;
            }
            else
            {
                BankField selected = (BankField)e.RowObject;
                if (!selected.Enable)
                {
                    e.Canceled = true;
                    labelError.Text = LanguageUtil.钱袋已停用_无法编辑;
                    return;
                }

                foreach (BankField bf in BankField.GetBankField)
                    bf.Default = false;

                listViewEntry.SetObjects(BankField.GetBankField);
            }
        }

        private void OnCellClick(object sender, CellClickEventArgs e)
        {
            labelError.ResetText();
            listViewEntry.SelectedItem = e.Item;
            if (listViewEntry.SelectedObject != null)
            {
                bank = (BankField)listViewEntry.SelectedObject;
                buttonEnable.Text = bank.Enable ? LanguageUtil.禁用 : LanguageUtil.启用;
            }
            else
                bank = null;


        }

        private void OnCellRightClick(object sender, CellRightClickEventArgs e)
        {
            if (bank == null)
                return;

            contextMenuStrip1.Items.Clear();
            if (bank.Balance > 0)
            {
                for (int i = 0; i < BankField.GetBankField.Count; i++)
                {
                    if (BankField.GetBankField[i].Id == bank.Id)
                        continue;

                    ToolStripMenuItem item = new ToolStripMenuItem(
                        LanguageUtil.调整到 + BankField.GetBankField[i].Name);
                    item.Tag = BankField.GetBankField[i];
                    contextMenuStrip1.Items.Add(item);
                }
            }
            else
            {
                ToolStripMenuItem item = new ToolStripMenuItem(bank.Enable ? LanguageUtil.余额不足 : LanguageUtil.钱袋已停用_无法编辑);
                item.Enabled = false;
                item.ForeColor = Color.White;
                contextMenuStrip1.Items.Add(item);
            }

            contextMenuStrip1.Show(MousePosition);
        }

        private void OnStartEditCell(object sender, BrightIdeasSoftware.CellEditEventArgs e)
        {
            if (!bank.Enable)
            {
                e.Cancel = true;
                labelError.Text = LanguageUtil.钱袋已停用_无法编辑;
                return;
            }

            if (e.Column.AspectName == "Balance")
            {
                labelError.Text = LanguageUtil.钱袋余额不能修改;
                e.Cancel = true;
            }
        }

        private void OnFinishEditCell(object sender, BrightIdeasSoftware.CellEditEventArgs e)
        {
            switch (e.Column.AspectName)
            {
                case "Credit":
                    decimal de=0;
                    decimal.TryParse(e.NewValue.ToString(), out de);
                    if (de !=0)
                        bank.Credit = de;

                    break;
                case "Url":
                    bank.Url = (string)e.NewValue;
                    break;
                case "Name":
                    bank.Name = (string)e.NewValue;
                    break;
            }
        }


        BackgroundWorker bgworker = null;
        Hashtable ht = new Hashtable();
        private void buttonCheck_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(LanguageUtil.此操作耗时_是否继续, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                labelError.Text = LanguageUtil.数据检测中_请稍后;
                buttonCheck.Enabled = false;
                this.ControlBox = false;
                bgworker = new BackgroundWorker();
                bgworker.DoWork += new DoWorkEventHandler(bgworker_DoWork);
                bgworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgworker_RunWorkerCompleted);
                bgworker.RunWorkerAsync();
            }
        }

        void bgworker_DoWork(object sender, DoWorkEventArgs e)
        {
            ht.Clear();
            foreach (BankField bank in BankField.GetBankField.FindAll(bf => { return bf.Enable; }))
            {
                decimal d = 0;
                foreach (EntryField entry in EntryField.GetEntryField.FindAll(ef => { return ef.BankId == bank.Id; }))
                    d += entry.Money;

                if (d != bank.Balance)
                    ht[bank] = d;
            }
        }

        void bgworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            buttonCheck.Enabled = true;
            labelError.ResetText();
            this.ControlBox = true;

            if (ht.Count == 0)
            {
                labelError.Text = LanguageUtil.数据一致;
                buttonCheck.Enabled = false;
                return;
            }

            buttonRepair.Enabled = true;
            TextDecoration decoration = new TextDecoration(LanguageUtil.数据不一致, 255);
            decoration.Alignment = ContentAlignment.MiddleCenter;
            decoration.Font = new Font(this.Font.Name, this.Font.SizeInPoints + 2);
            decoration.TextColor = Color.Firebrick;
            decoration.Rotation = -20;
            ((OLVListItem)listViewEntry.Items[listViewEntry.Items.Count - 1]).Decoration = decoration;
        }

        private void buttonRepair_Click(object sender, EventArgs e)
        {
            buttonRepair.Enabled = false;
            ((OLVListItem)listViewEntry.Items[listViewEntry.Items.Count - 1]).Decoration = null;

            foreach (DictionaryEntry de in ht)
                ((BankField)de.Key).Balance = (decimal)de.Value;

            listViewEntry.RefreshObjects(BankField.GetBankField);

            Program.SaveKMD = true;
        }

        private void OnHyperLinkClick(object sender, IsHyperlinkEventArgs e)
        {
            e.Url = e.Text;
            MessageBox.Show(e.Url);
        }

        private void OnContextMenuItemClick(object sender, ToolStripItemClickedEventArgs e)
        {
            labelError.ResetText();
            decimal de = 0;
            BankField expenseBank = (BankField)listViewEntry.SelectedObject;
            BankField incomeBank = (BankField)e.ClickedItem.Tag;
            TextForm s = new TextForm();
            s.Init(LanguageUtil.钱袋调拨, LanguageUtil.钱袋之间资金流动, "");

            if (s.ShowDialog() == DialogResult.OK)
                decimal.TryParse(s.GetText, out de);
            if (de <= 0)
                labelError.Text = LanguageUtil.调拨金额必须为正数;
            else if (de > expenseBank.Balance)
                labelError.Text = LanguageUtil.余额不足;
            else
            {
                GroupField expenseGroup = GroupField.GetDefaultGroup(false);
                if (expenseGroup == null)
                    return;

                GroupField incomeGroup = GroupField.GetDefaultGroup(true);
                if (incomeGroup == null)
                    return;

                EntryField expenseEntry = new EntryField(expenseGroup.Id);
                EntryField incomeEntry = new EntryField(incomeGroup.Id);

                expenseEntry.columnName = LanguageUtil.钱袋调拨;
                expenseEntry.GroupId = expenseGroup.Id;
                expenseEntry.Money = de;
                expenseEntry.Date = DateTime.Now;
                expenseEntry.columnNote = LanguageUtil.从 + expenseBank.Name + " " + LanguageUtil.调出 + LanguageUtil.到 + incomeBank.Name;
                expenseEntry.BankId = expenseBank.Id;
                expenseEntry.EntryType = KMDEntryType.Transfer;
                expenseEntry.Mark = incomeEntry.Id.ToString();
                expenseEntry.AddRowToDataTable();

                incomeEntry.columnName = LanguageUtil.钱袋调拨;
                incomeEntry.GroupId = incomeGroup.Id;
                incomeEntry.Money = de;
                incomeEntry.Date = DateTime.Now;
                incomeEntry.columnNote = LanguageUtil.从 + expenseBank.Name + " " + LanguageUtil.调入 + LanguageUtil.到 + incomeBank.Name;
                incomeEntry.BankId = incomeBank.Id;
                incomeEntry.EntryType = KMDEntryType.Transfer;
                incomeEntry.Mark = expenseEntry.Id.ToString();
                incomeEntry.AddRowToDataTable();


                listViewEntry.RefreshObjects(BankField.GetBankField);
                reloadEntryField = true;
            }
        }
    }
}